<script setup lang="ts" name="SystemDictData">
import { storeToRefs } from 'pinia'
import { useAppStoreWithOut } from '@/store/modules/app'
import { getIntDictOptions } from '@/utils/dict'
import { DICT_TYPE } from '@/enums/dictEnums'
import { dateFormatter } from '@/utils/dateUtil'
import { DictApi, DictTypeType } from '@/api/system/dict/index'
import { dataToFile } from '@/components/Excel/src/helper'
import DictDataForm from './DictDataForm.vue'
import { checkPermit, computedOperateWidth } from '@/utils/permit'
const appStore = useAppStoreWithOut()
const { systemConfig } = storeToRefs(appStore)


const route = useRoute() // 路由
const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
const total = ref(0) // 列表的总页数
const list = ref([]) // 表格数据
const queryLoading = ref(false) // 列表加载中：1）列表数据加载；2）查询按钮禁用；3）重置按钮禁用
const queryParams = ref({
  pageIndex: 1,
  pageSize: 20,
  label: '',
  type: route.params.dictType as string,
  status: undefined
})
const queryFormRef = ref() // 搜索的表单
const dictTypeList = ref<DictTypeType[]>() // 字典类型的列表


/** 查询字典类型列表 */
const getList = async () => {
  queryLoading.value = true
  try {
    const data = await DictApi.Data.page(queryParams.value)
    list.value = data.list
    total.value = data.total
  } finally {
    queryLoading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageIndex = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryParams.value.pageIndex = 1
  queryParams.value.pageSize = 20
  queryParams.value.label = ''
  queryParams.value.type = route.params.dictType as string
  queryParams.value.status = undefined
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id, queryParams.value.type)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await DictApi.Data.delete(id)
    message.success(t('message.del', 'success'))
    // 刷新列表
    await getList()
  } catch { }
}

const ExcelExportDialogRef = ref()

const filedList = ref([
  { key: 'id', value: 'ID' },
  { key: 'label', value: t('sys.dict', 'label') },
  { key: 'value', value: t('sys.dict', 'value') },
  { key: 'status', value: t('common', 'status') },
  { key: 'dict_type', value: t('sys.dict', 'type') },
  { key: 'color_type', value: t('sys.dict', 'colorType') },
  { key: 'css_class', value: t('sys.dict', 'cssClass') },
  { key: 'sort', value: t('common', 'sort') },
  { key: 'remark', value: t('common', 'remark') }
])
/** 导出按钮操作 */
const handleExport = async () => {
  ExcelExportDialogRef.value.open(getDictTypeLabel())
}

const exportDone = async (res) => {
  if (res.dataScope === 1) {
    dataToFile(list.value, res)
  } else if (res.dataScope === 3) {
    const allList = await DictApi.Data.export(queryParams.value)
    dataToFile(allList, res)
  }
}

const getDictTypeLabel = () => {
  const res = dictTypeList.value?.filter(item => {
    return item.type === queryParams.value.type
  })
  if (res && res.length > 0) {
    return res[0].name
  } else {
    return null
  }
}
/** 初始化 **/
onMounted(async () => {
  getList()
  // 查询字典（精简)列表
  dictTypeList.value = await DictApi.Type.simple()
})
</script>

<template>
  <PageCard>
    <ContentFormTable>
      <template #header>
        <ElForm ref="queryFormRef" :model="queryParams" :inline="true">
          <ElFormItem :label="t('sys.dict', 'title')" prop="type" class="!w-240px">
            <el-select v-model="queryParams.type" :placeholder="t('sys.dict.rules', 'title')" clearable filterable @change="handleQuery">
              <el-option v-for="item in dictTypeList" :key="item.type" :label="item.name" :value="item.type" />
            </el-select>
          </ElFormItem>
          <el-form-item :label="t('sys.dict', 'label')" prop="label" class="!w-240px">
            <el-input v-model="queryParams.label" :placeholder="t('sys.dict.rules', 'label')" clearable @keyup.enter="handleQuery" />
          </el-form-item>
          <ElFormItem :label="t('common', 'status')" prop="status">
            <el-select v-model="queryParams.status" class="!w-160px" clearable :placeholder="t('sys.dict.rules', 'dataStatus')" @change="handleQuery">
              <el-option v-for="dict in getIntDictOptions(DICT_TYPE.COMMON_STATUS)" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </ElFormItem>
          <ElFormItem>
            <el-button type="primary" :disabled="queryLoading" icon="Search" @click="handleQuery">{{ t('action', 'search') }}</el-button>
            <el-button icon="Refresh" :disabled="queryLoading" @click="resetQuery">{{ t('action', 'reset') }}</el-button>
            <el-button v-if="checkPermit(['system:dict:data:create'])" type="success" icon="Plus" @click="openForm('create')">{{ t('action', 'create') }}</el-button>
            <CButton v-if="checkPermit(['system:dict:data:export'])" type="warning" :disabled="queryLoading" :onClick="handleExport" preIcon="ri:export-line" :title="t('action', 'export')" />
          </ElFormItem>
        </ElForm>
      </template>
      <template #content>
        <el-table v-loading="queryLoading && systemConfig.loadingType === 'module'" :data="list" border>
          <el-table-column type="index" :label="t('common', 'index')" width="60" align="center" />
          <el-table-column prop="label" :label="t('sys.dict', 'label')" align="center" />
          <el-table-column prop="value" :label="t('sys.dict', 'value')" align="center" />
          <el-table-column prop="status" :label="t('common', 'status')" width="90" align="center">
            <template #default="scope">
              <dict-tag :type="DICT_TYPE.COMMON_STATUS" :value="scope.row.status" />
            </template>
          </el-table-column>
          <el-table-column prop="color_type" :label="t('sys.dict', 'colorType')" align="center">
            <template #default="scope">
              <el-tag v-if="scope.row.color_type" :type="scope.row.color_type">{{ scope.row.color_type }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="css_class" :label="t('sys.dict', 'cssClass')" align="center" />
          <el-table-column prop="sort" :label="t('common', 'sort')" width="60" align="center" />
          <el-table-column prop="remark" :label="t('common', 'remark')" show-overflow-tooltip align="center" />
          <el-table-column prop="create_time" :label="t('common', 'createTime')" :formatter="dateFormatter" align="center" />
          <el-table-column v-if="checkPermit(['system:dict:data:update', 'system:dict:data:delete'])" prop="operate" :label="t('common', 'operate')" :width="computedOperateWidth(['system:dict:data:update', 'system:dict:data:delete'])" align="center" fixed="right">
            <template #default="scope">
              <el-button v-if="checkPermit(['system:dict:data:update'])" type="primary" icon="Edit" @click="openForm('update', scope.row.id)" />
              <el-button v-if="checkPermit(['system:dict:data:delete'])" type="danger" icon="Delete" @click="handleDelete(scope.row.id)" />
            </template>
          </el-table-column>
        </el-table>
      </template>
      <template #footer>
        <Pagination v-model:limit="queryParams.pageSize" v-model:page="queryParams.pageIndex" :total="total" :disabled="queryLoading" @pagination="getList" />
        <DictDataForm ref="formRef" :dictTypeList="dictTypeList" @success="getList" />
        <ExcelExportDialog ref="ExcelExportDialogRef" :filename="t('sys.dict', 'title')" :hasSelected="false" :fieldList="filedList" @success="exportDone" />
      </template>
    </ContentFormTable>
  </PageCard>
</template>

<style scoped lang="scss">
.el-table {
  width: 100%;
  height: 100%;
}
</style>
